<template>
  <div class="upload-box">
    <el-upload
        v-model:file-list="fileList"
        class="upload-demo"
        action="#"
        :auto-upload="false"
        :show-file-list="false"
        :limit="2"
        ref="upload"
        :on-exceed="handleExceed"
    >
      <slot></slot>
    </el-upload>
    <div class="preview-list">
      <div v-for="(item,index) in previewList" :key="index">
        <img :src="item.url"
             style="width: 200px;height: 200px;margin-left: 10px"/>
        <el-icon @click="handleDelete(item)">
          <Delete/>
        </el-icon>
      </div>

    </div>
  </div>
</template>

<script setup>
import {nextTick, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {genFileId} from 'element-plus'
// import {Delete} from '@element-plus/icons-vue'
const upload = ref()
const previewList = ref([])
const fileList = defineModel()
defineOptions({
  name: 'MUpload'
})

function checkFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      const img = new Image()
      img.src = reader.result
      img.onload = () => {
        const {width, height} = img
        if (file.size > 1024*220) {
          ElMessage.error('图片不能超过2MB')
          resolve(false)
        } else {
          resolve(true)
        }
      }
    }
  })
}

function handleExceed(files, fileList) {
  upload.value?.clearFiles()
  previewList.value = []
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

watch(() => fileList.value, async (newFiles) => {
  await nextTick()
  const uidList = previewList.value.map((item) => item?.uid)
  for (let i = 0; i <newFiles.length ; i++) {
    if(uidList.includes(newFiles[i].uid)) continue
    if (newFiles[i]?.raw) {
      const flag = await checkFile(newFiles[i].raw)
      if (flag) {
        previewList.value.push({
          url: URL.createObjectURL(newFiles[i].raw),
          name: newFiles[i].name,
          uid: newFiles[i].uid
        })
      }else {
        fileList.value = fileList.value.filter((item) => item.uid!== newFiles[i].uid)
      }
    }
      if (newFiles[i].url) {
        previewList.value.push({
          url: newFiles[i].url,
          name: newFiles[i].name,
          uid: newFiles[i].uid
        })
      }
  }
}, {
  immediate: true
})

function handleDelete(item) {
  fileList.value = fileList.value.filter((file) => file.uid !== item.uid)
  previewList.value = previewList.value.filter((file) => file.uid !== item.uid)
}
</script>


<style scoped lang="scss">
.upload-box {

}
</style>